package com.user_chat.chat.tools;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
public class JwtUtils {

    private static final String SECRET_KEY = "HandSomeBoyLiangWenJun20010710";//密钥

    /**
     * 生成token
     * @param username
     * @param isAdmin
     * @return
     */
    public String generateToken(String username,boolean isAdmin) {
        //根据用户名+是否是管理员设置字段，利用HMAC256和密钥进行签名
        JWTCreator.Builder builder = JWT.create();
        String sign = builder.withClaim("username", username)
                .withClaim("isAdmin", isAdmin).sign(Algorithm.HMAC256(SECRET_KEY));
        return sign;
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public void verify(String token){
        //指定HMAC256和密钥生成的JWT验证对象来进行验证
        JWT.require(Algorithm.HMAC256(SECRET_KEY)).build().verify(token);  // 如果验证通过，则不会把报错，否则会报错
    }


    /**
     * 获取token中payload
     * @param token
     * @return
     */
    public DecodedJWT getToken(String token){
        return JWT.require(Algorithm.HMAC256(SECRET_KEY)).build().verify(token);
    }

    /**
     * 获取数据
     * @param token
     * @return
     */
    public HashMap<String,Object>getDateMap(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SECRET_KEY)).build().verify(token);
        String username = verify.getClaim("username").asString();
        Boolean isAdmin = verify.getClaim("isAdmin").asBoolean();

        HashMap<String, Object> data = new HashMap<>();

        data.put("username",username);
        data.put("isAdmin",isAdmin);

        return data;
    }
}
